import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCaseStore = defineStore('case', () => {
  // 案件列表
  const caseList = ref([])
  const currentCase = ref(null)
  const caseFilters = ref({
    status: '', // pending, in-progress, closed
    type: '', // litigation, settlement
    dateRange: []
  })
  
  // 案件统计
  const caseStats = ref({
    total: 5,
    pending: 2,
    inProgress: 2,
    closed: 1
  })
  
  // 计算属性
  const pendingCases = computed(() => 
    caseList.value.filter(case_ => case_.status === 'pending')
  )
  
  const inProgressCases = computed(() => 
    caseList.value.filter(case_ => case_.status === 'in-progress')
  )
  
  const closedCases = computed(() => 
    caseList.value.filter(case_ => case_.status === 'closed')
  )
  
  // 设置案件列表
  const setCaseList = (cases) => {
    caseList.value = cases
    updateStats()
  }
  
  // 设置当前案件
  const setCurrentCase = (case_) => {
    currentCase.value = case_
  }
  
  // 添加案件
  const addCase = (case_) => {
    caseList.value.push(case_)
    updateStats()
  }
  
  // 更新案件
  const updateCase = (caseId, updates) => {
    const index = caseList.value.findIndex(case_ => case_.id === caseId)
    if (index !== -1) {
      caseList.value[index] = { ...caseList.value[index], ...updates }
      updateStats()
    }
  }
  
  // 删除案件
  const deleteCase = (caseId) => {
    const index = caseList.value.findIndex(case_ => case_.id === caseId)
    if (index !== -1) {
      caseList.value.splice(index, 1)
      updateStats()
    }
  }
  
  // 更新统计信息
  const updateStats = () => {
    caseStats.value = {
      total: caseList.value.length,
      pending: pendingCases.value.length,
      inProgress: inProgressCases.value.length,
      closed: closedCases.value.length
    }
  }
  
  // 设置筛选条件
  const setFilters = (filters) => {
    caseFilters.value = { ...caseFilters.value, ...filters }
  }
  
  // 获取筛选后的案件列表
  const getFilteredCases = () => {
    let filtered = caseList.value
    
    if (caseFilters.value.status) {
      filtered = filtered.filter(case_ => case_.status === caseFilters.value.status)
    }
    
    if (caseFilters.value.type) {
      filtered = filtered.filter(case_ => case_.type === caseFilters.value.type)
    }
    
    if (caseFilters.value.dateRange && caseFilters.value.dateRange.length === 2) {
      filtered = filtered.filter(case_ => {
        const caseDate = new Date(case_.createdAt)
        return caseDate >= caseFilters.value.dateRange[0] && 
               caseDate <= caseFilters.value.dateRange[1]
      })
    }
    
    return filtered
  }
  
  return {
    caseList,
    currentCase,
    caseFilters,
    caseStats,
    pendingCases,
    inProgressCases,
    closedCases,
    setCaseList,
    setCurrentCase,
    addCase,
    updateCase,
    deleteCase,
    setFilters,
    getFilteredCases
  }
}) 